<?php
/**
 * Created by PhpStorm.
 * User: ztos
 * Date: 2017/12/13
 * Time: 上午9:41
 */

namespace app\index\controller;

use app\common\model\PayLog;
use app\index\model\Activity as ActivityModel;
use app\index\model\ActivityComment;
use app\index\model\ActivityPeople;
use app\index\model\WechatUser;
use MongoDB\Driver\WriteError;
use Hooklife\ThinkphpWechat\Wechat as WechatServer;
use think\Log;
use wechat\Weixinpay;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
use app\common\model\PayLog as PayLogModel;
use wxpay\JsApiPay;
use wxpay\WxPayApi;
use wxpay\WxPayConfig;
use wxpay\database\WxPayUnifiedOrder;

class Activity extends Base
{
    //活动报名主页
    public function index()
    {
        $activity = new ActivityModel();
        $list = $activity->getListbyParkid();
        $this->assign('list', json_encode($list));
        return $this->fetch();
    }

    //活动报名详情页
    public function detail()
    {
        $data = input('');
        $info = ActivityModel::where('id', $data['id'])->find();
        $comment = ActivityComment::where(['activity_id' => $data['id'], 'openid' => session('openid'), 'status' => ['in', [0, 1]]])->select();
        $is_sgin = count($comment) > 0 ? "yes" : "no";
        $info['is_sign'] = $is_sgin;
        $openid = session('openid');
        //判断用户是否关注
        $res = WechatServer::app()->user->get($openid);
        $info['subscribe'] = $res['subscribe'];
        $count = ActivityComment::where(['activity_id' => $data['id'], 'status' => ['in', [1]]])->count();
        $jssdk = WechatServer::app()->js->config(array('onMenuShareTimeline', 'onMenuShareAppMessage'), true);
        $this->assign('js_sdk', $jssdk);
        $this->assign('count', $count);
        $this->assign('info', json_encode($info));
        return $this->fetch();


    }


    //报名
    public function signUp()
    {
        $data = input('');
        $activity = new ActivityModel();
        $Comment = new ActivityComment();
        $openid = session('openid');
        //判断用户是否关注
        $user = WechatServer::app()->user->get($openid);

        $people = new ActivityPeople();
        if (IS_POST) {
            $activity->startTrans();
            $activityInfo = $activity->where('id', $data['activity_id'])->lock(true)->find();
            //活动不处于 开始报名 状态
            if ($activityInfo['status'] != 2) {
                $activity->rollback();

                return $this->error('当前活动不可报名中');
            }
            //当前时间已超过活动开始时间
            if (time() > $activityInfo['start_time']) {
                $activity->rollback();

                return $this->error('当前活动不可报名中');
            }
            //已关注
            if ($user['subscribe'] == 1) {
                $map = [
                    'activity_id' => $data['activity_id'],
                    'openid' => session('openid'),
                    'type_id' => $data['typeid'],
                    'name' => $data['name'],
                    'mobile' => $data['mobile'],
                    'remark' => $data['remark'],
                    'status' => 1
                ];
                $re = $Comment->save($map);
                if ($re) {
                    $peopleList = array();
                    foreach ($data['activity_people'] as $key => $value) {
                        $peopleList[$key]['comment_id'] = $Comment->getLastInsID();
                        $peopleList[$key]['name'] = $value['name'];
                        $peopleList[$key]['mobile'] = $value['mobile'];
                        $peopleList[$key]['people_card'] = $value['people_card'];
                        $peopleList[$key]['emergency_contact'] = $value['emergency_contact'];
                    }
                    $res = $people->saveAll($peopleList);
                    if ($res) {
                        $activity->commit();

                        return $this->success('报名成功');
                    } else {
                        $activity->rollback();

                        return $this->error("保存失败(出行人)");
                    }
                } else {
                    $activity->rollback();

                    return $this->error("保存失败(订单)");
                }
            } //未关注
            else {
                $activity->rollback();

                return $this->error("请先关注再报名", 'index/index/code');
            }
            //$data['openid']=$openid;
        }
        $activityInfo = $activity->where('id', $data['activity_id'])->find();
        $data = ['type' => json_decode($activityInfo['type']),
            'activity_id' => $activityInfo['id'],
            'front_cover' => $activityInfo['front_cover'],
            'status' => $activityInfo['status'],
            'registration_required' => $activityInfo['registration_required']
        ];
        $this->assign('data', json_encode($data));

        return $this->fetch('sign_up');
    }

    /**
     * 微信支付接口
     * @return \think\response\Json
     */
   /* public function pay()
    {
        $activity = new ActivityModel();
        $datas = input('');
        if (!$this->checkPayDate($datas)) {

            return json(['code' => 0, 'data' => '参数错误']);
        }
        $id = input('id');
        $typeid = input('typeid');
        $activity_info = $activity->where(['id' => $id])->find();
        if ($activity_info) {
            $type = json_decode($activity_info['type']);
            if (!empty($type)) {
                foreach ($type as $k => $v) {
                    $v = object_array($v);
                    if (intval($typeid) == intval($v['typeid'])) {
                        $points = $v['number'] * $v['price'] * 100;
                    }
                }
            }
        } else {

            return json(['code' => 0, 'data' => "该活动不存在"]);
        }
        if (!isset($points)) {

            return json(['code' => 0, 'data' => "参数错误"]);
        }

        $openid = session('openid');
        //同一个商户号下唯一商户订单号
        $out_trade_no = date('YmdHis', time()) . 'jhyscm' . rand(10000, 20000) . rand(10000, 99999);
        $data = [
            'body' => "test",
            'out_trade_no' => $out_trade_no,
            'total_fee' => $points, //充值金额 单位为分
            'spbill_create_ip' => get_client_ip(),
            'trade_type' => 'JSAPI',
            'openid' => $openid,
//            'nonce_str' => random(12) //随机字符串
        ];
        //获取微信配置
        $wxConf = config('wechat');
        //实例化easyWeChat
        $wxApp = new Application($wxConf);
        $order = new Order($data);
        //dump($order);
        //实例化支付
        $payment = $wxApp->payment;
        //预支付
        $result = $payment->prepare($order);
        //$result = $payObj->unifiedOrder($data);
        if ($result['return_code'] !== 'SUCCESS') {

            return json(['error_msg' => '购买发起失败！']);
        } else if ($result['result_code'] !== 'SUCCESS') {

            return json(['error_msg' => '购买发起失败！']);
        } else if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {

            $result['timestamp'] = time();
            $payLog = [
                'order_id' => $data['out_trade_no'], //唯一订单号
                'openid' => $openid,
                'money' => $points,
                'aid' => $activity_info['id'],
                'time' => time(),
                'status' => 0,

            ];
            PayLogModel::create($payLog);

            return json(['code' => 1, 'data' => $result]);
        }

    }*/

    /**
     * 检验参数
     * @param $data
     * @return bool
     */
    public function checkPayDate($data)
    {
        if (empty($data)) {

            return false;
        }
        if (!isset($data['activity_id'])) {

            return false;
        }
        unset($data['remark']);
        foreach ($data as $k => $v) {
            if (empty($v)) {

                return false;
            }
        }

        return true;
    }

    /**
     * @param  out_trade_no 订单号
     * @param  money 金额
     * @param  jylsh 交易流水号
     * @return \think\response\Json
     */
    public function refund()
    {
        $data = input('');
        if ($this->checkRefundData($data) == false) {

            return json(['code' => 0, 'data' => '参数错误']);
        }
        $wxConf = config('wechat');
        //实例化easyWeChat
        $wxApp = new Application($wxConf);
        //实例化支付
        $payment = $wxApp->payment;
        $result = $payment->refund($data['out_trade_no'], $data['jylsh'], $data['money'] * 100);
        if ($result['return_code'] != "SUCCESS") {

            return json(['code' => 0,'data' => "退款失败"]);
        }elseif ($result['result_code'] != "SUCCESS"){

            return json(['code' => 0,'data' => $result['err_code_des']]);
        }else{
            $map = ['jylsh' => $data['jylsh']];
            $paylog_model = new ActivityComment();
            $res = $paylog_model->where($map)->update(['status' => 3]);
            if (!$res){
                Log::info("退款成功，未修改数据状态值");
            }

            return json(['code' => 1,'data' => "退款成功"]);
        }
    }

    /**
     * 检测退款参数
     * @param $data
     * @return bool
     */
    public function checkRefundData($data)
    {
        $refundData = ['out_trade_no', 'jylsh', 'money'];
        foreach ($refundData as $key => $value) {
            if (!isset($data[$value]) || empty($data[$value])) {

                return false;
            }
        }

        return true;
    }

    /**
     * 微信支付接口
     * @return \think\response\Json|void
     */
    public function wxPay()
    {
        $data = input('');
        $activity = new ActivityModel();
        $Comment = new ActivityComment();
        $openid = session('openid');
        //判断用户是否关注
        $user = WechatServer::app()->user->get($openid);
        $people = new ActivityPeople();
        if (!$this->checkPayDate($data)) {

            return json(['code' => 0, 'data' => '参数错误']);
        }
        $id = input('activity_id');
        $typeid = input('typeid');
        $activity_info = $activity->where(['id' => $id])->find();
        if ($activity_info) {
            $type = json_decode($activity_info['type']);
            if (!empty($type)) {
                foreach ($type as $k => $v) {
                    $v = object_array($v);
                    if (intval($typeid) == intval($v['typeid'])) {
                        $points = $v['number'] * $v['price'] * 100;
                    }
                }
            }
        } else {

            return json(['code' => 0, 'data' => "该活动不存在"]);
        }
        if (!isset($points)) {

            return json(['code' => 0, 'data' => "参数错误"]);
        }
        $activity->startTrans();
        $activityInfo = $activity->where('id', $data['activity_id'])->lock(true)->find();
        //活动不处于 开始报名 状态
        if ($activityInfo['status'] != 2) {
            $activity->rollback();

            return $this->error('当前活动不可报名中');
        }
        //当前时间已超过活动开始时间
        if (time() > $activityInfo['start_time']) {
            $activity->rollback();

            return $this->error('当前活动不可报名中');
        }
        //已关注
        if ($user['subscribe'] == 1) {
            //同一个商户号下唯一商户订单号
            $outTradeNo = WxPayConfig::MCHID . date("YmdHis");
            $map = [
                'activity_id' => $data['activity_id'],
                'openid' => session('openid'),
                'type_id' => $data['typeid'],
                'name' => $data['name'],
                'mobile' => $data['mobile'],
                'remark' => $data['remark'],
                'status' => 0,
                'out_trade_no' => $outTradeNo,
                'money' => $points,
            ];
            $re = $Comment->save($map);
            if ($re) {
                $peopleList = array();
                foreach ($data['activity_people'] as $key => $value) {
                    $peopleList[$key]['comment_id'] = $Comment->getLastInsID();
                    $peopleList[$key]['name'] = $value['name'];
                    $peopleList[$key]['mobile'] = $value['mobile'];
                    $peopleList[$key]['people_card'] = $value['people_card'];
                    $peopleList[$key]['emergency_contact'] = $value['emergency_contact'];
                }
                $res = $people->saveAll($peopleList);
                if ($res) {
                    $activity->commit();
                   /* //同一个商户号下唯一商户订单号
                   // $out_trade_no = date('YmdHis', time()) . 'jhyscm' . rand(10000, 20000) . rand(10000, 99999);
                    $out_trade_no = '123456789987654321';
                    $points = "1000";
                    $data = [
                        'trade_type' => 'JSAPI',
                        'body' => "毅行达人活动报名费用",
                        'out_trade_no' => $out_trade_no,
                        'total_fee' => $points,
                        'openid' => $openid,
                    ];
                    //获取微信配置
                    $wxConf = config('wechat');
                    //实例化easyWeChat
                    $wxApp = new Application($wxConf);
                    $order = new Order($data);

                    //dump($order);
                    //实例化支付
                    $payment = $wxApp->payment;
                    //预支付
                    $result = $payment->prepare($order);
                    //$result = $payObj->unifiedOrder($data);*/
                    $tools = new JsApiPay();
                    //统一下单
                    $input = new WxPayUnifiedOrder();
                    $input->setBody("毅行达人活动报名费用");
                    $input->setAttach("test");
                    $input->setOutTradeNo($outTradeNo);
                    $input->setTotalFee($points); //积分是一角 微信支付以分为单位
                    $input->setTimeStart(date("YmdHis"));
                    $input->setTimeExpire(date("YmdHis", time() + 600));
                    $input->setGoodsTag("Reward");
                    $input->setNotifyUrl("http://jh.0519ztnet.com/index/wechat/notify");
                    $input->setTradeType("JSAPI");
                    $input->setOpenid($openid);
                    $result = WxPayApi::unifiedOrder($input);
                    if ($result['return_code'] !== 'SUCCESS') {

                        return json(['error_msg' => '购买发起失败！']);
                    } else if ($result['result_code'] !== 'SUCCESS') {

                        return json(['error_msg' => '购买发起失败！']);
                    } else if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
                        $jsApiParameters = $tools->getJsApiParameters($result);

                        //$prepayId = $result['prepay_id'];
                        //$json = $payment->configForAppPayment($prepayId,false);

                        return $this->success('报名成功', '', $jsApiParameters);
                    } else {
                        $activity->rollback();

                        return $this->error("保存失败(出行人)");
                    }
                } else {
                    $activity->rollback();

                    return $this->error("保存失败(订单)");
                }
            } //未关注
            else {
                $activity->rollback();

                return $this->error("请先关注再报名", 'index/index/code');
            }
        }
    }

    /*public function refundReturnUrl(){

        $wxConf = config('wechat');
        //实例化easyWeChat
        $wxApp = new Application($wxConf);
        //实例化支付
        $payment = $wxApp->payment;
        $payment->getRefundNotify(function ($message, $reqInfo, $fail){
            $activity_comment_model = new ActivityComment();
            if ($message['return_code'] == "SUCCESS"){
                if ($reqInfo['refund_status'] == "SUCCESS"){
                    $out_trade_no = $reqInfo['out_trade_no'];
                    $map = ['out_trade_no' => $out_trade_no];
                    $result = $activity_comment_model->where($map)->update(['status' => 2,'refund_time' => $reqInfo['success_time'] ]);
                    if ($result){

                        return true;
                    }

                    return false;
                }
            }
            return false;
        });
    }*/
    /*public function test()
    {
        $openid = session('openid');

        $out_trade_no = '123456789987654321';
        $points = "1000";
        $data = [
            'trade_type' => 'JSAPI',
            'body' => "毅行达人活动报名费用",
            'out_trade_no' => $out_trade_no,
            'total_fee' => $points,
            'openid' => $openid,
        ];
        var_dump($data);
        //获取微信配置
        $wxConf = config('wechat');
        //实例化easyWeChat
        $wxApp = new Application($wxConf);
        $order = new Order($data);

        //dump($order);
        //实例化支付
        $payment = $wxApp->payment;
        //预支付
        $result = $payment->prepare($order);
        //$result = $payObj->unifiedOrder($data);
        if ($result['return_code'] !== 'SUCCESS') {

            return json(['error_msg' => '购买发起失败！']);
        } else if ($result['result_code'] !== 'SUCCESS') {

            return json(['error_msg' => '购买发起失败！']);
        } else if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {

            $result['timestamp'] = time();
            //$prepayId = $result['prepay_id'];
            //$json = $payment->configForAppPayment($prepayId,false);

            return json($result);
        }
    }*/

    /**
     * 微信支付测试，备用
     * @return \think\response\Json
     */
   /* public function test1(){
        $openid = session('openid');

        $tools = new JsApiPay();
        //统一下单
        $points = 10;
        $money = $points;
        $outTradeNo = WxPayConfig::MCHID . date("YmdHis");
        $input = new WxPayUnifiedOrder();
        $input->setBody("积分购买");
        $input->setAttach("test");
        $input->setOutTradeNo($outTradeNo);
        $input->setTotalFee($points * 10); //积分是一角 微信支付以分为单位
        $input->setTimeStart(date("YmdHis"));
        $input->setTimeExpire(date("YmdHis", time() + 600));
        $input->setGoodsTag("Reward");
        $input->setNotifyUrl("http://xgq.0571ztnet.com/index/wechat/notify");
        $input->setTradeType("JSAPI");
        $input->setOpenid($openid);
        $order = WxPayApi::unifiedOrder($input);
        //return json($order);
        $jsApiParameters = $tools->getJsApiParameters($order);

        return json(['success' => true, 'data' => $jsApiParameters]);
    }*/
}